/**
 * 统一的API响应格式工具函数
 */

import { serializeBigInt } from './bigint';

export interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  message?: string;
  code?: string;
  timestamp: string;
}

export interface PaginatedResponse<T = any> extends ApiResponse<T[]> {
  pagination?: {
    page: number;
    pageSize: number;
    total: number;
    totalPages: number;
  };
}

/**
 * 创建成功响应
 */
export function createSuccessResponse<T>(
  data?: T,
  message?: string
): ApiResponse<T> {
  return {
    success: true,
    data: data ? serializeBigInt(data) : data,
    message: message || 'Success',
    timestamp: new Date().toISOString(),
  };
}

/**
 * 创建错误响应
 */
export function createErrorResponse(
  message: string,
  code?: string,
  data?: any
): ApiResponse {
  return {
    success: false,
    data,
    message,
    code,
    timestamp: new Date().toISOString(),
  };
}

/**
 * 创建分页响应
 */
export function createPaginatedResponse<T>(
  data: T[],
  pagination: {
    page: number;
    pageSize: number;
    total: number;
  },
  message?: string
): PaginatedResponse<T> {
  return {
    success: true,
    data: serializeBigInt(data),
    message: message || 'Success',
    pagination: {
      ...pagination,
      totalPages: Math.ceil(pagination.total / pagination.pageSize),
    },
    timestamp: new Date().toISOString(),
  };
}

/**
 * 常用的错误代码
 */
export const ERROR_CODES = {
  // 通用错误
  INTERNAL_ERROR: 'INTERNAL_ERROR',
  INVALID_REQUEST: 'INVALID_REQUEST',
  VALIDATION_ERROR: 'VALIDATION_ERROR',
  
  // 认证相关
  UNAUTHORIZED: 'UNAUTHORIZED',
  FORBIDDEN: 'FORBIDDEN',
  TOKEN_EXPIRED: 'TOKEN_EXPIRED',
  INVALID_TOKEN: 'INVALID_TOKEN',
  
  // 资源相关
  NOT_FOUND: 'NOT_FOUND',
  ALREADY_EXISTS: 'ALREADY_EXISTS',
  CONFLICT: 'CONFLICT',
  
  // 业务相关
  INSUFFICIENT_BALANCE: 'INSUFFICIENT_BALANCE',
  OPERATION_FAILED: 'OPERATION_FAILED',
} as const;

/**
 * 常用的成功消息
 */
export const SUCCESS_MESSAGES = {
  CREATED: '创建成功',
  UPDATED: '更新成功',
  DELETED: '删除成功',
  RETRIEVED: '获取成功',
  OPERATION_SUCCESS: '操作成功',
} as const;

/**
 * 常用的错误消息
 */
export const ERROR_MESSAGES = {
  INTERNAL_ERROR: '服务器内部错误',
  INVALID_REQUEST: '请求参数无效',
  VALIDATION_ERROR: '数据验证失败',
  UNAUTHORIZED: '未授权访问',
  FORBIDDEN: '禁止访问',
  NOT_FOUND: '资源不存在',
  ALREADY_EXISTS: '资源已存在',
  OPERATION_FAILED: '操作失败',
} as const;
